package com.noassertions.web;

import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.noassertions.data.DAOInterface;
import com.noassertions.domain.User;

@Controller
public class HomeController {
	protected final Log log = LogFactory.getLog(getClass());
	private DAOInterface dao;
    private MessageSource messageSource;

    @Autowired
    public HomeController(DAOInterface dao, MessageSource messageSource) {
        this.dao = dao;
        this.messageSource = messageSource;
    }  
	
	@RequestMapping("/home")
	public String getRider(Model model) throws MalformedURLException, IOException
	{
		// All of our home logic is taken care of in our AJAX viewer
		
		// Is a user current logged in? Check for null since we setup spring security to permitAll requests to this URL
		// TODO this business of checking for a string (which indicates that user is not authenticated) is a total hack and should be factored out
		if (! (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String)) {
			UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			User user = dao.getUserByemailAddress(principal.getUsername());
			model.addAttribute("emailAddress", user.getEmailaddress());
		}
		
		return "home";
	}
}